<template>
	<div class="user-info">

		<main class="content">
			<!-- 头像 -->
			<section class="info-item avatar-section" @click="handleAvatarClick">
				<div class="title">
					<uni-icons type="contact" size="20" color="gray"></uni-icons>
					头像
				</div>
				<label for="avatar-upload" class="value">
					 <image class="avatar" :src="avatarUrl" @tap="chooseFromAlbum"></image>
				</label>
				<!-- 文件选择器 -->
				<input id="avatar-upload" type="file" accept="image/*" @change="onAvatarChange"
					style="display: none;" />
				<div :class="[avatarState]" @click.stop="handleAvatarAction">{{ avatarButtonText }}</div>
			</section>

			<!-- 其他信息项 -->
			<section v-for="(item, index) in infoItems" :key="index" class="info-item" @click="handleClick(item)">
				<div class="title">
					<uni-icons :type="item.icon" size="20" color="gray"></uni-icons> <!-- 动态设置图标类型 -->
					{{ item.title }}
				</div>
				<input v-if="item.editing" v-model="item.value" :placeholder="item.placeholder" class="input-field"
					style="color: gray;" />
				<div v-else class="value">{{ item.value || item.placeholder }}</div>
				<div :class="[item.state]" @click.stop="handleAction(item)">{{ item.buttonText }}</div>
			</section>
		</main>
		<!-- 底部 -->
		<footer class="footer">
			<button class="save-btn" @click="saveInfo()">
				<uni-icons type="refreshempty" size="25" color="#fff"></uni-icons>
				保存个人信息
			</button>
		</footer>
		<!-- 收货地址 -->

		<!-- 地址选择模态框 -->
		   <view class="address-modal" v-if="showAddressModal">
		     <view class="modal-content">
		       <view class="modal-header">
		         <text>请选择地址</text>
		         <button @click="closeAddressModal" class="close">&times;</button>
		       </view>
		       <view class="modal-body">
		         <!-- 使用 picker 组件进行多列选择 -->
		         <picker mode="region" :value="selectedRegion" @change="handleRegionChange">
		           <view class="picker-placeholder">
		            {{ selectedRegion[0] }} {{ selectedRegion[1] }} {{ selectedRegion[2] || '点击选择地区' }}
		         </view>
		         </picker>
		       </view>
		       <view class="modal-footer">
		         <button @click="confirmAddress">下一步</button>
		       </view>
		     </view>
		   </view>
		   
		   <!-- 完善收货地址弹窗 -->
		   <view class="address-detail-modal" v-if="showAddressDetailModal">
		     <view class="modal-content">
		       <view class="modal-header">
		         <text>完善收货地址</text>
		         <button @click="closeAddressDetailModal" class="close">&times;</button>
		       </view>
		       <view class="modal-body">
		         <!-- 显示选择的地址 -->
		         <view class="selected-address">
		           选择的地址: {{ selectedRegion[0] }} {{ selectedRegion[1] }} {{ selectedRegion[2] }}
		         </view>
		         <textarea v-model="detailedAddress" placeholder="请输入详细地址"></textarea>
		       </view>
		       <view class="modal-footer">
		         <button @click="saveDetailedAddress">保存</button>
		       </view>
		     </view>
		   </view>
		
		<!-- 签署协议模态框 -->
		<div class="contract-modal" v-if="showContractModal">
		  <div class="modal-content">
		    <div class="modal-header">
		      <h3>签署服务协议</h3>
		      <button @click="closeContractModal" class="close">&times;</button>
		    </div>
		    <div class="modal-body">
		      <p style="color: red;">请先点击蓝色文字认真阅读每项协议，勾选后则代表您已知晓并同意对应协议和平台声明。</p>
		      <checkbox-group @change="handleCheckboxChange">
		        <div class="agreement-item">
		          <label>
		            <checkbox value="agreement1" :checked="agreements.agreement1" />
		            <a href="#" @click.prevent="openAgreement('agreement1')" class="agreement-link">《代收代付服务协议》</a>
		          </label>
		        </div>
		        <div class="agreement-item">
		          <label>
		            <checkbox value="agreement2" :checked="agreements.agreement2" />
		            <a href="#" @click.prevent="openAgreement('agreement2')" class="agreement-link">《免责声明服务协议》</a>
		          </label>
		        </div>
		      </checkbox-group>
		    </div>
		    <div class="modal-footer">
		      <button @click="signContract">我同意并签署</button>
		    </div>
		  </div>
		</div>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				avatarUrl: 'https://example.com/default-avatar.png',
				avatarState: 'actionone', // 初始化为修改状态
				avatarButtonText: '修改', // 初始化为修改文本
				
				infoItems: [{
						title: '微信昵称',
						icon: 'person',
						value: '',
						placeholder: '超好用的电子评价卡',
						state: 'action',
						buttonText: '完善',
						editing: false
					},
					{
						title: '姓名',
						icon: 'list',
						value: '',
						placeholder: '请输入姓名',
						state: 'action',
						buttonText: '完善',
						editing: false
					},
					{
						title: '手机号',
						icon: 'phone',
						value: '',
						placeholder: '未填写',
						state: 'action',
						buttonText: '完善',
						editing: false
					},
					{
						title: '收货地址',
						icon: 'location',
						value: '',
						placeholder: '未填写',
						state: 'action',
						buttonText: '完善',
						editing: false
					},
					{
						title: '签署协议',
						icon: 'bars',
						value: '',
						placeholder: '未签署服务协议',
						state: 'action',
						buttonText: '完善',
						editing: false
					}
				],
				showAddressModal: false,
				showAddressDetailModal: false,
				selectedRegion: ['', '', ''], // 初始化为空数组
				detailedAddress: '123',
				showContractModal: false,
				agreements: {
				  agreement1: false,
				  agreement2: false
				},
				ifAllsigned:0,
				id:0,
				storeId:0
			};
		},
		onLoad(options) {
			console.log("merchantinfo页面id：" + options.status);
			this.id = options.status;
			this.storeId = options.storeId;
			console.log(this.id,this.storeId);
			this.merchantData(this.id,this.storeId);
			// this.findMerchantInfo();
			},
		methods: {
			
			chooseFromAlbum() {
			  // 从相册中选择图片作为头像
			  uni.chooseImage({
			    count: 1, // 只允许选择一张图片
			    sizeType: ['original', 'compressed'], // 可以选择原图或压缩后的图片
			    sourceType: ['album'], // 只能从相册选择
			    success: (res) => {
			      this.avatarUrl = res.tempFilePaths[0]; // 更新头像URL
			    }
			  });
			},

			saveDetailedAddress() {
			  if (!this.detailedAddress) {
			  wx.showToast({
			    title: '请输入详细地址',
			    icon: 'none',
			    duration: 2000
			  });
			  return;
			}
			
			// 组合完整地址
			const fullAddress = `${this.selectedRegion[0]} ${this.selectedRegion[1]} ${this.selectedRegion[2]} ${this.detailedAddress}`;
			
			// 更新收货地址信息项
			const addressItem = this.infoItems.find(item => item.title === '收货地址');
			if (addressItem) {
			  addressItem.value = fullAddress;
			  addressItem.state = 'actionone';
			  addressItem.buttonText = '修改';
			}
			
			// 保存到本地存储
			wx.setStorageSync('detailedAddress', this.detailedAddress);
			wx.setStorageSync('selectedRegion', this.selectedRegion);
			
			wx.showToast({
			  title: '保存成功',
			  icon: 'success',
			  duration: 2000
			});
			
			this.showAddressDetailModal = false;
			},
			handleRegionChange(e) {
			 this.selectedRegion = e.detail.value;
			this.hasSelectedAddress = true; // 用户选择了地址后更新标志位
			console.log('Selected Region:', this.selectedRegion);
			},
			
			handleCheckboxChange(e) {
			  const values = e.detail.value;
			  this.agreements.agreement1 = values.includes('agreement1');
			  this.agreements.agreement2 = values.includes('agreement2');
			},
			
			goBack() {
				this.$router.back();
			},
			handleAvatarClick() {
				if (this.avatarState === 'actionone') {
					document.getElementById('avatar-upload').click(); // 触发文件选择器
				}
			},
			onAvatarChange(event) {
				const file = event.target.files[0];
				if (file) {
					const reader = new FileReader();
					reader.onload = e => {
						this.avatarUrl = e.target.result;
						this.prepareSaveAvatar(); // 准备保存头像
					};
					reader.readAsDataURL(file);
				}
			},
			prepareSaveAvatar() {
				this.avatarState = 'actiontwo';
				this.avatarButtonText = '保存';
			},
			saveAvatar() {
				console.log('头像已保存');
				this.avatarState = 'actionone';
				this.avatarButtonText = '修改';
			},
			handleAvatarAction() {
				switch (this.avatarState) {
					case 'actionone':
						this.handleAvatarClick();
						break;
					case 'actiontwo':
						this.saveAvatar();
						break;
				}
			},
			handleClick(item) {
				if (item.title === '收货地址') {
					this.showAddressModal = true;
				} else if (item.title === '签署协议') {
					this.showContractModal = true; // 显示服务协议模态框
				} else if (item.state === 'action') {
					this.prepareEdit(item);
				}
			},
			closeContractModal() {
				this.showContractModal = false;
			},
			signContract() {
				this.ifAllsigned = (this.agreements.agreement1&&this.agreements.agreement2) == true? this.ifAllsigned=1:this.ifAllsigned=0;
				console.log(this.ifAllsigned)
				if (!this.agreements.agreement1 || !this.agreements.agreement2) {
					wx.showToast({
						title: '请确保所有协议都已勾选！',
						icon: 'none', // 如果你不想要默认的成功图标
						duration: 2000 // 提示框显示的时间，单位为毫秒
					});
					return;
				}
				wx.showToast({
					title: '您已成功签署服务协议',
					icon: 'success', // 成功图标的显示
					duration: 2000 // 提示框显示的时间，单位为毫秒
				});
				this.closeContractModal();
				const item = this.infoItems.find(i => i.title === '签署协议');
				item.value = '您已签署';
				item.state = 'actiontwo'; // 或者其他表示已签署的状态
				item.buttonText = '保存';
			},
			// openAgreement(agreementId) {
			// 	alert(`查看 ${agreementId} 协议`);
			// },
			openAgreement(agreementId) {
				this.agreements[0] == false? true: false;
				this.agreements[1] == false? true: false;
			  wx.showModal({
			    title: '协议查看',
			    content: `您正在查看 ${agreementId} 协议`,
			    success(res) {
			      if (res.confirm) {
			        console.log('用户点击确定');
			      } else if (res.cancel) {
			        console.log('用户点击取消');
			      }
			    }
			  })

			},
			handleAction(item) {
				switch (item.state) {
					case 'action':
						this.prepareEdit(item);
						break;
					case 'actiontwo':
						this.saveInfoItem(item);
						break;
					case 'actionone':
						this.editInfo(item);
						break;
				}
			},
			prepareEdit(item) {
				item.editing = true;
				item.state = 'actiontwo';
				item.buttonText = '保存';
			},
			saveInfoItem(item) {
				item.editing = false;
				item.state = 'actionone'; // 改为新的修改状态
				item.buttonText = '修改';
			},
			editInfo(item) {
				item.editing = true;
				item.state = 'actiontwo';
				item.buttonText = '保存';
			},
			saveInfo() {
				uni.request({
				 url:'http://zhaoyang.nat300.top/app/update',//后端接口地址
				 method:'POST',// 请求方法，可以是 GET、POST、PUT、DELETE 等
				 data: {
					id:this.id,
					avatar:this.avatarUrl,
					nickname:this.infoItems[0].value,
					name:this.infoItems[1].value,
					phone:this.infoItems[2].value,
					address:this.infoItems[3].value,
					agreement:this.ifAllsigned,
				 //username:'user123',
				 //password:'password123',
				},//需要传递给后端的数据
				 header:{
				 'Content-Type':'application/json'//设置请求头
				 },
				 success(res){
				 console.log('请求成功',res.data);// 后端返回的数据
				 },
				 fail(err){
				 console.error('请求失败',err);
				 }
				 });
				wx.showModal({
					title: '提示',
					content: '保存信息成功，请先完善门店信息',
					showCancel: false, // 不显示取消按钮
					success:(res) => {
						if (res.confirm) {
							console.log('用户点击确定');
							// 在这里可以添加跳转到完善门店信息页面的逻辑
							// 后端返回数据
							
							console.log(this.id)
							uni.navigateTo({
								url: `/pages/storeset/storeset?status=${this.id}`
							})
						}
					}
				});
				console.log(this.infoItems);
				
			},
			async merchantData(id,storeId) {
			    try {
			      const response = await uni.request({
			        url: 'http://zhaoyang.nat300.top/app/find',
			        method: 'POST',
			        data: { 
						id:id,
						storeId:storeId,
						 },
			        header: { 'content-type': 'application/json' }
			      });
				  
			      if (response.statusCode === 200 && response.data) {
					// console.log(response)
			        const responseData = response.data;
					console.log(responseData.nickname);
					this.infoItems[0].value = responseData.nickname;
					this.infoItems[1].value = responseData.name;
					this.avatarUrl = responseData.avatar;
					this.infoItems[3].value=responseData.address;
					this.infoItems[2].value=responseData.phone
					this.infoItems[4].value="您已签署"
					this.agreements.agreement1=true;
					this.agreements.agreement2=true;
					// console.log(responseData);
					// console.log(this.infoItems[0]);
					// this.infoItems
					
			        uni.showToast({
			          title: '提交成功',
			          icon: 'success'
			        });
			      } else {
			        console.error('Server responded with status:', response.statusCode);
			        uni.showToast({
			          title: '获取数据失败，请重试。',
			          icon: 'none'
			        });
			      }
			    } catch (error) {
			      console.error('POST 请求失败:', error);
			      uni.showToast({
			        title: '提交失败，请重试',
			        icon: 'none'
			      });
			    }
			  },
			// async submitData(id) {
			//     console.log("当前用户id：" + id);
			//    await uni.request({
			//       url: 'http://zhaoyang.nat300.top/app/update',
			//       method: 'POST',
			//       data: {
			//         id: id,
			//       },
			//       header: {
			//         'content-type': 'application/json' // 默认值
			//       },
			//       success(response) {
			//         console.log('POST 请求成功:', response);
			//         uni.showToast({
			//           title: '提交成功',
			//           icon: 'success'
			//         });
			//       },
			//       fail(error) {
			//         console.error('POST 请求失败:', error);
			//         uni.showToast({
			//           title: '提交失败，请重试',
			//           icon: 'none'
			//         });
			//       }
			//     });
			// },
		closeAddressModal() {
			this.showAddressModal = false;
		},
		confirmAddress() {
			// this.infoItems.find(item => item.title === '收货地址').value =
			// 	`${this.selectedProvince} ${this.selectedCity} ${this.selectedDistrict}`;
			// this.showAddressModal = false;
			// this.showAddressDetailModal = true;
			 if (!this.selectedRegion[0] || !this.selectedRegion[1] || !this.selectedRegion[2]) {
			  wx.showToast({
			    title: '请选择完整地址',
			    icon: 'none',
			    duration: 2000
			  });
			  return;
			}
			this.showAddressModal = false;
			this.showAddressDetailModal = true;
					
		},
      closeAddressDetailModal() {
        this.showAddressDetailModal = false;
      },
      updateAddressButtonState(item) {
        if (item && item.value) {
          item.state = 'actiontwo';
          item.buttonText = '保存';
        } else {
          item.state = 'action';
          item.buttonText = '完善';
        }
      }
	// 	saveDetailedAddress() {
	// 		const addressItem = this.infoItems.find(item => item.title === '收货地址');
	// 		addressItem.value =
	// 			`${this.selectedProvince} ${this.selectedCity} ${this.selectedDistrict} ${this.detailedAddress}`;
	// 		this.showAddressDetailModal = false;
	// 		this.updateAddressButtonState(addressItem);
	// 	},

	// 	updateAddressButtonState(item) {
	// 		if (item && item.value) {
	// 			item.state = 'actiontwo';
	// 			item.buttonText = '保存';
	// 		} else {
	// 			item.state = 'action';
	// 			item.buttonText = '完善';
	// 		}
	// 	},
	// 	updateCity() {
	// 		// 根据所选省份更新城市列表
	// 		this.selectedCity = '';
	// 		this.selectedDistrict = '';
	// 		this.cities = [];
	// 		this.districts = [];

	// 		switch (this.selectedProvince) {
	// 			case '1':
	// 				this.cities = [{
	// 					id: '101',
	// 					name: '北京市'
	// 				}];
	// 				break;
	// 			case '2':
	// 				this.cities = [{
	// 					id: '201',
	// 					name: '上海市'
	// 				}];
	// 				break;
	// 			case '3':
	// 				this.cities = [{
	// 						id: '301',
	// 						name: '广州市'
	// 					},
	// 					{
	// 						id: '302',
	// 						name: '深圳市'
	// 					},
	// 					{
	// 						id: '303',
	// 						name: '珠海市'
	// 					}
	// 				];
	// 				break;
	// 		}
	// 	},

	// 	updateDistrict() {
	// 		// 根据所选城市更新区县列表
	// 		this.selectedDistrict = '';
	// 		this.districts = [];

	// 		switch (this.selectedCity) {
	// 			case '101':
	// 				this.districts = [{
	// 						id: '10101',
	// 						name: '东城区'
	// 					},
	// 					{
	// 						id: '10102',
	// 						name: '西城区'
	// 					}
	// 				];
	// 				break;
	// 			case '201':
	// 				this.districts = [{
	// 						id: '20101',
	// 						name: '黄浦区'
	// 					},
	// 					{
	// 						id: '20102',
	// 						name: '徐汇区'
	// 					}
	// 				];
	// 				break;
	// 			case '301':
	// 				this.districts = [{
	// 						id: '30101',
	// 						name: '天河区'
	// 					},
	// 					{
	// 						id: '30102',
	// 						name: '白云区'
	// 					}
	// 				];
	// 				break;
	// 			case '302':
	// 				this.districts = [{
	// 						id: '30201',
	// 						name: '福田区'
	// 					},
	// 					{
	// 						id: '30202',
	// 						name: '南山区'
	// 					}
	// 				];
	// 				break;
	// 			case '303':
	// 				this.districts = [{
	// 					id: '30301',
	// 					name: '香洲区'
	// 				}];
	// 				break;
	// 		}
	// 	},
	// watch: {
	// 	selectedProvince(newVal) {
	// 		const province = this.provinces.find(p => p.id === newVal);
	// 		this.selectedProvinceName = province ? province.name : '';
	// 		this.updateCity();
	// 	},
	// 	selectedCity(newVal) {
	// 		const city = this.cities.find(c => c.id === newVal);
	// 		this.selectedCityName = city ? city.name : '';
	// 		this.updateDistrict();
	// 	},
	// 	selectedDistrict(newVal) {
	// 		const district = this.districts.find(d => d.id === newVal);
	// 		this.selectedDistrictName = district ? district.name : '';
	// 	}
	}
	};
</script>

<style scoped>
/* 整体部分 */
.user-info {
  font-family: Arial, sans-serif;
}

/* 头像部分 */
.info-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px;
  background-color: #fff;
  border: 1px solid #ddd;
  margin-bottom: 10px;
}

.avatar-section {
  position: relative;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
}

.title {
  color: black;
  font-weight: 800;
  flex-grow: 1;
}

.input-field {
  flex-grow: 1;
  padding: 5px;
  margin-left: 10px;
  border-radius: 4px;
}

.action,
.actiontwo,
.actionone {
  color: #fff;
  cursor: pointer;
  padding: 10px;
  border-radius: 15px;
}

.action {
  background-color: #c44e49;
}

.actiontwo {
  background-color: #2b7bfd;
}

.actionone {
  background-color: #77c94b;
}

.footer {
  padding: 20px;
  background-color: #fff;
  width: 90%;
}

.save-btn {
  width: 90%;
  padding: 10px;
  background-color: rgb(119, 201, 75);
  color: #fff;
  border: none;
  border-radius: 50px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 地址选择相关样式 */
.picker-placeholder {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin: 10px 0;
}

.selected-address {
  margin-bottom: 10px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.modal-body textarea {
  width: 100%;
  height: 100px;
  margin-top: 10px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

/* 签署合同部分 */
.contract-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: #fff;
  padding: 30px;
  border-radius: 8px;
  width: 80%;
  max-width: 600px;
}

.modal-body p {
  white-space: pre-line;
  color: red;
}

.agreement-item {
  margin-bottom: 0px;
}

.agreement-link {
  color: blue;
  text-decoration: none;
}

.agreement-link:hover {
  text-decoration: underline;
}

.modal-footer button {
  margin-top: 15px;
  padding: 10px 20px;
  background-color: #77c94b;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
</style>